package com.lhkk.inventoryvehicle.common;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context; // 需要传入 Context
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit; // 用于日期比较

/**
 * 文件工具类
 */
public class LogFileUtils {
    private static final String TAG = "LogFileUtils";
    private static final SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    private static final SimpleDateFormat fileNameTimeFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    private static final int maxDays = 7; // 保存天数上限
    private static final String LOG_SUBDIRECTORY = "logs"; // Download下的子文件夹名

    // 需要一个 Context 实例来执行 MediaStore 操作
    private static Context applicationContext;

    public static void init(Context context) {
        applicationContext = context.getApplicationContext();
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String content) {
        if (applicationContext == null) {
            Log.e(TAG, "LogFileUtils not initialized. Call init(context) first.");
            return;
        }

        Runnable runnable = () -> {
            String time = mDateTimeFormat.format(new Date(System.currentTimeMillis()));
            String strContent = time + "  " + content + "\r\n"; // 每次写入时，都换行写

            try {
                // 确保 Context 存在
                if (applicationContext == null) {
                    Log.e(TAG, "Application context is null, cannot write log.");
                    return;
                }

                // 获取日志文件的 Uri，如果不存在则创建
                Uri logFileUri = getOrCreateLogFileUri(applicationContext);
                if (logFileUri == null) {
                    Log.e(TAG, "Failed to get or create log file URI.");
                    return;
                }

                // 通过 Uri 获取 OutputStream，并以追加模式写入
                ContentResolver resolver = applicationContext.getContentResolver();
                OutputStream os = null;
                try {
                    // "wa" 表示写入并追加。如果文件不存在，也会创建。
                    os = resolver.openOutputStream(logFileUri, "wa");
                    if (os != null) {
                        os.write(strContent.getBytes(StandardCharsets.UTF_8)); // 使用 UTF-8 编码
                    } else {
                        Log.e(TAG, "OutputStream is null for URI: " + logFileUri);
                    }
                } finally {
                    if (os != null) {
                        os.close();
                    }
                }
                Log.d(TAG, "Log written to: " + logFileUri.toString());

                // 执行日志清理
                deleteOldLogs(applicationContext);

            } catch (Exception e) {
                Log.e(TAG, "Error on write File: " + e.getMessage(), e);
            }
        };
        // 假设你有一个 ThreadPoolInstance 类来管理线程池
        ThreadPoolInstance.INSTANCE.getSingleThreadExecutor().execute(runnable);
    }

    /**
     * 获取或创建当天日志文件的 Uri
     *
     * @param context Context
     * @return 文件的 Uri，如果失败则为 null
     */
    private static Uri getOrCreateLogFileUri(Context context) {
        String fileName = fileNameTimeFormat.format(new Date(System.currentTimeMillis())) + ".txt";
        ContentResolver resolver = context.getContentResolver();
        Uri fileUri = null;

        // 1. 尝试查询文件是否已存在
        fileUri = findLogFileUri(resolver, fileName);

        if (fileUri == null) {
            // 文件不存在，创建新的文件
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
            // 设置相对路径，在 Downloads 目录下创建 'logs' 子文件夹
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + File.separator + LOG_SUBDIRECTORY);

            try {
                fileUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
                if (fileUri == null) {
                    Log.e(TAG, "Failed to create new log file in MediaStore.");
                }
            } catch (Exception e) {
                Log.e(TAG, "Error inserting new MediaStore entry: " + e.getMessage(), e);
            }
        }
        return fileUri;
    }

    /**
     * 查询 Downloads/logs/ 目录下是否存在指定文件。
     *
     * @param resolver ContentResolver
     * @param fileName 要查找的文件名 (e.g., "2025-06-23.txt")
     * @return 如果找到，返回文件的 Uri；否则返回 null。
     */
    private static Uri findLogFileUri(ContentResolver resolver, String fileName) {
        // 构建查询条件，查找指定文件名和相对路径的文件
        String selection = MediaStore.MediaColumns.DISPLAY_NAME + "=? AND " +
                MediaStore.MediaColumns.RELATIVE_PATH + "=?";
        String[] selectionArgs = new String[]{
                fileName,
                Environment.DIRECTORY_DOWNLOADS + File.separator + LOG_SUBDIRECTORY + File.separator // MediaStore的RELATIVE_PATH末尾包含/
        };

        Uri collection = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
        Uri fileUri = null;

        try (Cursor cursor = resolver.query(
                collection,
                new String[]{MediaStore.MediaColumns._ID}, // 只需要_ID来构建Uri
                selection,
                selectionArgs,
                null
        )) {
            if (cursor != null && cursor.moveToFirst()) {
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                fileUri = Uri.withAppendedPath(collection, String.valueOf(id));
                Log.d(TAG, "Found existing log file URI for: " + fileName + ", URI: " + fileUri);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error querying existing log file: " + e.getMessage(), e);
        }
        return fileUri;
    }

    /**
     * 删除 Downloads/logs/ 目录下超过 maxDays 的日志文件。
     *
     * @param context Context
     */
    private static void deleteOldLogs(Context context) {
        ContentResolver resolver = context.getContentResolver();
        Uri collection = MediaStore.Downloads.EXTERNAL_CONTENT_URI;

        // 构建查询条件，查找 Downloads/logs/ 目录下的所有txt文件
        String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=? AND " +
                MediaStore.MediaColumns.MIME_TYPE + "=?";
        String[] selectionArgs = new String[]{
                Environment.DIRECTORY_DOWNLOADS + File.separator + LOG_SUBDIRECTORY + File.separator,
                "text/plain"
        };

        try (Cursor cursor = resolver.query(
                collection,
                new String[]{MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DISPLAY_NAME},
                selection,
                selectionArgs,
                null
        )) {
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME));

                    // 从文件名中解析日期 (e.g., "2025-06-23.txt" -> "2025-06-23")
                    String dateString = fileName.replace(".txt", "");
                    try {
                        Date fileDate = fileNameTimeFormat.parse(dateString);
                        if (fileDate != null) {
                            long diffInMs = System.currentTimeMillis() - fileDate.getTime();
                            long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMs);

                            if (diffInDays > maxDays) {
                                // 超过指定天数，删除文件
                                Uri fileToDeleteUri = Uri.withAppendedPath(collection, String.valueOf(id));
                                int deletedRows = resolver.delete(fileToDeleteUri, null, null);
                                if (deletedRows > 0) {
                                    Log.d(TAG, "Deleted old log file: " + fileName);
                                } else {
                                    Log.w(TAG, "Failed to delete old log file: " + fileName);
                                }
                            }
                        }
                    } catch (ParseException e) {
                        Log.e(TAG, "Failed to parse date from file name: " + fileName, e);
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error deleting old logs: " + e.getMessage(), e);
        }
    }


    // 读取指定目录下的所有TXT文件的文件内容 (此方法在 Downloads 目录下需要通过 MediaStore Uri 读取)
    // 原始的 File Input Stream 方式不再适用，需要修改
    // private static String getFileContent(File file) { ... } // 不再直接使用 File 读取

    // 新的读取指定日志文件内容的方法 (通过 Uri 读取)
    public static String getLogFileContent(Context context, String date) {
        if (applicationContext == null) {
            Log.e(TAG, "LogFileUtils not initialized. Call init(context) first.");
            return "";
        }
        ContentResolver resolver = context.getContentResolver();
        String fileName = date + ".txt"; // 根据日期构造文件名
        Uri fileUri = findLogFileUri(resolver, fileName);

        if (fileUri == null) {
            Log.d(TAG, "Log file not found for date: " + date);
            return "日志文件不存在或已过期。";
        }

        StringBuilder content = new StringBuilder();
        try (InputStream inStream = resolver.openInputStream(fileUri);
             InputStreamReader inputReader = new InputStreamReader(inStream, StandardCharsets.UTF_8);
             BufferedReader buffReader = new BufferedReader(inputReader)) {

            String line;
            while ((line = buffReader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            Log.e(TAG, "Error reading log file content: " + e.getMessage(), e);
            return "读取日志文件失败: " + e.getMessage();
        }
        return content.toString();
    }


    // deleteSingleFile 方法也需要改为通过 MediaStore Uri 删除
    // private static void deleteSingleFile(String filePath) { ... } // 不再直接使用 File 删除
}